package com.lfy.modules.safety.controller;

import com.lfy.encrypt.AESUtil;
import com.lfy.modules.common.anno.NoNeedLog;


import com.lfy.modules.safety.domain.vo.HeartVO;

import com.lfy.modules.safety.domain.vo.VisitorVO;
import com.lfy.modules.safety.statistics.heartbeat.HeartBeatCache;

import com.lfy.modules.safety.statistics.vistor.VisitorRecordCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@RestController
@RequestMapping("/heart")
@Slf4j
public class HeartController {
    @Value("${ase.key}")
    public String aseKey;
    @Resource
    private ThreadPoolExecutor secondaryThreadPool;
    /**
     * 接收心跳数据
     * @param vo 心跳数据
     */
    @PostMapping("/ping")
    @NoNeedLog
    public void ping(@RequestBody @Validated HeartVO vo) {
        if(vo.getId()==null || vo.getUrl()==null){
            return;
        }
        try {
            String id = AESUtil.decryptString(vo.getId(), aseKey);
            HeartBeatCache.addHeartBeat(vo.getUrl(),id,System.currentTimeMillis());
            RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
            secondaryThreadPool.execute(() -> {
                RequestContextHolder.setRequestAttributes(requestAttributes);
                VisitorRecordCache.addVisitor(vo.getUrl());
            });
        } catch (Exception ignored) {

        }

    }
    @GetMapping("/test")
    @NoNeedLog
    public List<VisitorVO> test() {
        List<VisitorVO> lfy = VisitorRecordCache.getYesterdayBetweenSevenCount("lfy");
        return lfy;
    }


}
